import React from 'react'
import PropTypes from 'prop-types'

class Input extends React.Component {
    constructor(props) {
        super(props)
        this.state = { title: '' }
    }
    render() {
        return <div>
            <input type="text" value={this.state.title} onChange={this.onTitleChange}/>
            <button onClick={this.onSubmit}>提交</button>
        </div>
    }
    onTitleChange = e => {
        this.setState({title: e.target.value})
    }
    onSubmit = e => {
        const { submitTitle } = this.props
        submitTitle(this.state.title)
        this.setState({title: ''})
    }
}

// props 类型检查
Input.propTypes = {
    submitTitle: PropTypes.func.isRequired
}

class List extends React.Component {
    // constructor(props) {
    //     super(props)
    // }
    render() {
        const {list} = this.props

        return <ul>{list.map((item, index) => {
            // 必填，不能是index或者random
            return <li key={item.id}>index: {index}; title: {item.title}</li>
        })}</ul>
    }
}

// props 类型检查（必须有的对象数组）
List.propTypes = {
    list: PropTypes.arrayOf(PropTypes.object).isRequired
}

class TodoListDemo extends React.Component {
    constructor(props) {
        super(props)
        this.state = { list: [
            {id: 'id-1', title: '标题1'},
            {id: 'id-2', title: '标题2'},
            {id: 'id-3', title: '标题3'},
        ] }
    }
    render() {
        return <div>
            <h3>组件</h3>
            <div>
                <Input submitTitle={this.onSubmitTitle}/>
                <List list={this.state.list}/>
            </div>
        </div>
    }
    onSubmitTitle = title => {
        this.setState({
            list: this.state.list.concat({
                id: `id-${Date.now()}`,
                title
            })
        })
    }
}

export default TodoListDemo